<?php

namespace app\command\babyTree;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use \app\common\model\BBTArtical;

\think\Loader::import('QueryList.vendor.autoload');
use QL\QueryList;

class BBTYunqi extends Command
{
    protected function configure()
    {
        $this->setName('bbt_yunqi_spider')->setDescription('Grab baby tree parenting articles');
    }

    protected function execute(Input $input, Output $output)
    {
        # 40个孕期，共计40周
        #https://m.babytree.com/week/weekly/youer_1_1;
        #https://m.babytree.com/week/weekly/youer_2_1;
    	
        if(!($url = $this->getUrl())){
            $output->writeln("12 month has grabed");
            return ;
        }

        // 获取规则
        $rules = $this->getRules();
        // 获取数据
        $hj = QueryList::Query($url, $rules);
        $data = $hj->getData(function($x){
            return $x;
        });
        

        $level_type = $this->getLevelType($this->weekly);

        $artical_data = [
            'title' => $data[0]['title'],
            'artical' => $data[0]['articl'],
            'bbt_type' => 'yunqi',               // 孕期
            'bbt_level' => $level_type['level'],             // 幼儿
            'type_desc' => $level_type['desc'],            // 幼儿
            'week' => $this->weekly,            // 幼儿
        ];

        BBTArtical::create($artical_data);

        $output->writeln('complete');
    }

    protected function getUrl() {

        $options = [
            // 缓存类型为File
            'type'   => 'File', 
             // 缓存有效期为永久有效
            'expire' => 0,
             // 指定缓存目录
            'path'   => CACHE_PATH . 'bbt/yunqi/', 
        ];

        if(!($weekly = cache('weekly', '', $options))) {
            $weekly = 4;
        }

        if($weekly > 40) {
            return false;
        }

        $this->weekly = $weekly;

        cache('weekly', ($weekly+1), $options);

        $url = 'https://m.babytree.com/week/weekly/yunqi_%d_1';
        return $url = sprintf($url, $weekly);
    }

    protected function getRules() {
        return [
            "title"=>['.weekly-nav .title', 'text'],
            "articl"=>['.week-articl', 'html'],
        ];
    }

    protected function getLevelType($week) {
        $data = ['level'=>'', 'desc'=>''];

        if($week < 13) {
            $data = ['level'=>'yunzao', 'desc'=>'孕早期'];
        } else if($week > 12 && $week < 29) {
            $data = ['level'=>'yunzhong', 'desc'=>'孕中期'];
        } else {
            $data = ['level'=>'yunwan', 'desc'=>'孕晚期'];
        }

        return $data;
    }
}
